import java.awt.BorderLayout;
import java.awt.Color;
import java.awt.Frame;
import java.awt.GridBagConstraints;
import java.awt.GridBagLayout;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.KeyEvent;
import java.awt.event.KeyListener;
import java.awt.event.WindowEvent;

import javax.swing.JButton;
import javax.swing.JDialog;
import javax.swing.JLabel;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.border.LineBorder;

/**
 * 
 */

/**
 * @author andris
 *
 */
public class LoginDialog extends JDialog implements KeyListener,ActionListener{

	private static final long serialVersionUID = 5164961447109075438L;
	
	private JLabel lbUsername;
	private JLabel lbPassword;
	
	private JTextField tfUsername;
	private JPasswordField pfPassword;
	
	public LoginDialog(Frame parent){
		super(parent,"DB-Credentials",true);
		initialize();
		
		setDefaultCloseOperation(DISPOSE_ON_CLOSE);
	}
	
	public String[] askForLogin(){
		
		this.setVisible(true);
		
		String[] fields = new String[2];
		
		fields[0] = tfUsername.getText();
		fields[1] = String.copyValueOf(pfPassword.getPassword());
		
		return fields;
	}
	
	
	private void initialize(){
		

		JPanel panel = new JPanel(new GridBagLayout());
		GridBagConstraints cs = new GridBagConstraints();
		
		cs.fill = GridBagConstraints.HORIZONTAL;
		
		lbUsername = new JLabel("Username: ");
		cs.gridx = 0;
		cs.gridy = 0;
		cs.gridwidth = 1;
		panel.add(lbUsername, cs);
		
		tfUsername = new JTextField(20);
		tfUsername.addKeyListener(this);
		cs.gridx = 1;
		cs.gridy = 0;
		cs.gridwidth = 2;
		panel.add(tfUsername, cs);
		
		lbPassword = new JLabel("Password: ");
		cs.gridx = 0;
		cs.gridy = 1;
		cs.gridwidth = 1;
		panel.add(lbPassword, cs);
		
		pfPassword = new JPasswordField(20);
		pfPassword.addKeyListener(this);
		cs.gridx = 1;
		cs.gridy = 1;
		cs.gridwidth = 2;
		panel.add(pfPassword, cs);
		panel.setBorder(new LineBorder(Color.GRAY));
		

		JButton button = new JButton("Connect");
		
		button.addActionListener(this);
		
		getContentPane().add(panel,BorderLayout.CENTER);
		getContentPane().add(button,BorderLayout.PAGE_END);
		
		this.pack();
		setLocationRelativeTo(getParent());
	}

	@Override
	public void actionPerformed(ActionEvent e) {

		this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
		
	}

	@Override
	public void keyPressed(KeyEvent e) {
		if(e.getKeyCode() == KeyEvent.VK_ENTER){
			this.dispatchEvent(new WindowEvent(this, WindowEvent.WINDOW_CLOSING));
		}

		
	}

	@Override
	public void keyReleased(KeyEvent e) {

	}

	@Override
	public void keyTyped(KeyEvent e) {

	}
}
